const request = require('request')

/**
 * api json
 * @param {string} url
 * @param {any} data
 */
function apiJson(url, data = {}, config = {}) {
  return new Promise((resolve, reject) => {
    config = Object.assign(
      {
        headers: { 'Content-type': 'application/json;charset=UTF-8' }
      },
      config
    )
    request({
      url: url,
      method: 'POST',
      json: true,
      body: data,
      ...config,
      callback: (error, res, body) => {
        if (error) {
          reject(error)
        } else {
          resolve(body)
        }
      }
    })
  })
}

/**
 * api form
 * @param {string} url
 * @param {any} data
 */
function apiPost(url, data = {}, config = {}) {
  return new Promise((resolve, reject) => {
    request({
      url: url,
      method: 'POST',
      form: data,
      ...config,
      callback: (error, res, body) => {
        if (error) {
          reject(error)
        } else {
          resolve(body)
        }
      }
    })
  })
}

/**
 * api get
 * @param {string} url
 * @param {any} data
 */
function apiGet(url, data = {}, config = {}) {
  return new Promise((resolve, reject) => {
    request({
      url: url,
      method: 'GET',
      qs: data,
      ...config,
      callback: (error, res, body) => {
        if (error) {
          reject(error)
        } else {
          resolve(body)
        }
      }
    })
  })
}

module.exports = {
  request,
  apiGet,
  apiJson,
  apiPost
}
